const Mock = require('mockjs')

const machineList = []
const count = 30

for (let i = 0; i < count; i++) {
  machineList.push(Mock.mock({
    id: Mock.Random.increment(),
    name: Mock.Random.ctitle(3, 8) + '贩卖机',
    code: 'M' + Mock.Random.integer(1000, 9999),
    location: Mock.Random.ctitle(3, 8) + Mock.Random.pick(['号楼', '栋']) + Mock.Random.pick(['1层', '2层', '3层', '大厅', '门口']),
    status: Mock.Random.pick(['normal', 'fault', 'maintenance', 'offline']),
    description: Mock.Random.cparagraph(1, 2),
    lastMaintenanceTime: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss'),
    createTime: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss')
  }))
}

module.exports = [
  // 获取设备列表
  {
    url: '/api/machine/list',
    type: 'get',
    response: config => {
      const { name, code, status, pageNum = 1, pageSize = 10 } = config.query
      let filteredList = [...machineList].filter(item => {
        if (name && item.name.indexOf(name) < 0) return false
        if (code && item.code.indexOf(code) < 0) return false
        if (status && item.status !== status) return false
        return true
      })

      const pageList = filteredList.slice((pageNum - 1) * pageSize, pageNum * pageSize)

      return {
        code: 200,
        message: 'success',
        data: {
          list: pageList,
          total: filteredList.length
        }
      }
    }
  },

  // 添加设备
  {
    url: '/api/machine/add',
    type: 'post',
    response: config => {
      const newMachine = config.body
      newMachine.id = Mock.Random.increment()
      newMachine.createTime = Mock.Random.datetime('yyyy-MM-dd HH:mm:ss')
      machineList.unshift(newMachine)
      return {
        code: 200,
        message: '添加成功',
        data: newMachine
      }
    }
  },

  // 更新设备
  {
    url: '/api/machine/update',
    type: 'post',
    response: config => {
      const updatedMachine = config.body
      const index = machineList.findIndex(item => item.id === updatedMachine.id)
      if (index !== -1) {
        machineList.splice(index, 1, updatedMachine)
        return {
          code: 200,
          message: '修改成功',
          data: updatedMachine
        }
      } else {
        return {
          code: 404,
          message: '设备不存在'
        }
      }
    }
  },

  // 删除设备
  {
    url: '/api/machine/delete',
    type: 'post',
    response: config => {
      const { id } = config.body
      const index = machineList.findIndex(item => item.id === id)
      if (index !== -1) {
        machineList.splice(index, 1)
        return {
          code: 200,
          message: '删除成功'
        }
      } else {
        return {
          code: 404,
          message: '设备不存在'
        }
      }
    }
  }
]